﻿using Gufa.Entity;
using Gufa.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Gufa.Repositories
{
    public class BaseRepository<T> where T : class, new()
    {
        protected readonly GufaDBContext gufaDBContext;
        public BaseRepository(GufaDBContext gufaDBContext)
        {
            this.gufaDBContext = gufaDBContext;
        }
        public Task<bool> AddEntity(T entity)
        {
            gufaDBContext.Set<T>().Add(entity);

            return Task.FromResult(true);
        }

        public Task<bool> DeleteEntity(T entity)
        {
            gufaDBContext.Set<T>().Remove(entity);
            return Task.FromResult(true);
        }

        public IQueryable<T> LoadEntities(Expression<Func<T, bool>> whereLambda)
        {
            return gufaDBContext.Set<T>().Where(whereLambda);
        }

        public IQueryable<T> LoadPageEntities<S>(int pageIndex, int pageSize, out int totalCount, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderLamdba, bool isAsc)
        {
            var temp = gufaDBContext.Set<T>().Where(whereLambda);
            totalCount = temp.Count();
            if (isAsc)
            {
                // 升序排序
                temp = temp.OrderBy<T, S>(orderLamdba).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize);

            }
            else
            {
                temp = temp.OrderByDescending<T, S>(orderLamdba).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize);
            }
            return temp;
        }

        public Task<bool> UpdateEntity(T entity)
        {
            gufaDBContext.Set<T>().Update(entity);
            return Task.FromResult(true);
        }
    }
}
